package com.example.server.controller;

import com.baomidou.mybatisplus.extension.api.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@CrossOrigin
public class EmailController {
    @Resource
    private JavaMailSender javaMailSender;

    //读取yml文件中username的值并赋值给form
    @Value("${spring.mail.username}")
    private String from;

    @GetMapping("/sendEmail/{emailReceiver}")
    public R sendSimpleMail(@PathVariable String emailReceiver) {
        R r =new R<>();
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件发送者
        message.setFrom(from);
        // 设置邮件接收者
        message.setTo(emailReceiver);
        // 设置邮件的主题
        message.setSubject("【即刻运动】验证码");
        // 设置邮件的正文
        String[] letters = new String[] {
                "q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m",
                "A","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M",
                "0","1","2","3","4","5","6","7","8","9"};
        String stringBuilder ="";
        for (int i = 0; i < 6; i++) {
            stringBuilder = stringBuilder + letters[(int)Math.floor(Math.random()*letters.length)];
        }
        String text = "【即刻运动】尊敬的用户，欢迎使用即刻运动健身平台，您的邮箱验证码为: " + stringBuilder + " ,5分钟内有效，请及时输入。";
        message.setText(text);

        // 发送邮件
        try {
            javaMailSender.send(message);
            r.setCode(200);
            r.setMsg("发送成功");
            r.setData(stringBuilder);
            return r;
        } catch (MailException e) {
            e.printStackTrace();
        }
        r.setCode(500);
        r.setMsg("发送失败");
        return r;
    }
}